package constant.milk.cashbook.sms;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;

import constant.milk.cashbook.IntroActivity;
import constant.milk.cashbook.R;
import constant.milk.cashbook.bean.SmsData;
import constant.milk.cashbook.bean.SmsInputData;
import constant.milk.cashbook.bean.SmsReceiverData;
import constant.milk.cashbook.database.DBSelectQuery;
import constant.milk.cashbook.database.DbAdapter;
import constant.milk.cashbook.database.DbInsertQuery;
import constant.milk.cashbook.sms.parser.SmsParser;
import constant.milk.cashbook.util.MilkManager;
import constant.milk.cashbook.util.MilkUtil;
import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;

public class SmsService extends IntentService
{
	public static final String SMS_ARRAY = "SMS_ARRAY";
	
	private Context context;
	
	private String am_pm;
	private String hour;
	private String minute;
	
	public SmsService()
	{
		super("SmsService");
	}
	
	public SmsService(String name)
	{
		super(name);
	}
	
	@Override
	protected void onHandleIntent(Intent intent)
	{
		context = getApplicationContext();
		
		ArrayList<SmsReceiverData> list = intent.getParcelableArrayListExtra(SMS_ARRAY);
		
		for (int i = 0; i < list.size(); i++)
		{
			SmsReceiverData smsReceiverData = list.get(i);
			
			String address = smsReceiverData.getAddress();
			
			String body = smsReceiverData.getBody();
			
			if (address == null || address.length() == 0 || address.equals(""))
			{
				continue;
			}
			
			if (body == null || body.length() == 0 || body.equals(""))
			{
				continue;
			}
			
			SmsParser parser = new SmsParser(body);
			
			SmsInputData inputData = parser.messageParsing();
			
			if (inputData == null || parser.getAvailable() == false) 
			{
				continue;
			}
			
			int type = parser.getSmsType();
			
			if (type == -1 || type == SmsParser.HALBU_SMS)
			{
				continue;
			}
			
			String cardName = inputData.getName();
			
			DbAdapter db = DbAdapter.getInstance();
			MilkManager milkManager = new MilkManager(context, db);
			DBSelectQuery select = new DBSelectQuery(context, db);
			
			SmsData data = select.getSmsSelect(address, cardName);
			
			if (data == null 
					|| data.getAsset() == null  
					|| data.getAsset().equals("")
					|| data.getCardname() == null
					|| data.getCardname().equals(""))
			{
				continue;
			}
			
			boolean resultFlag = false;
			
			if (data.getAsset().equals(milkManager.getAssetStr(context.getString(R.string.creditCardAsset))))
			{
				if (type == SmsParser.OUT_SMS)
				{
					resultFlag = setInOutNormalData(context, db, data, inputData, 4);
				}
				else if (type == SmsParser.OUT_ATM_SMS)
				{
					resultFlag = setInOutMoveData(context, db, data, inputData);
				}
			}
			else if (data.getAsset().equals(milkManager.getAssetStr(context.getString(R.string.checkCardAsset))))
			{
				if (type == SmsParser.IN_SMS)
				{
					resultFlag = setInOutNormalData(context, db, data, inputData, 1);
				}
				else if (type == SmsParser.OUT_SMS)
				{
					resultFlag = setInOutNormalData(context, db, data, inputData, 0);
				}
				else if (type == SmsParser.IN_ATM_SMS)
				{
					resultFlag = setInOutMoveData(context, db, data, inputData);
				}
				else if (type == SmsParser.OUT_ATM_SMS)
				{
					resultFlag = setInOutMoveData(context, db, data, inputData);
				}
			}
			else if (data.getAsset().equals(milkManager.getAssetStr(context.getString(R.string.bankAsset))))
			{
				if (type == SmsParser.IN_SMS)
				{
					resultFlag = setInOutNormalData(context, db, data, inputData, 1);
				}
				else if (type == SmsParser.OUT_SMS)
				{
					resultFlag = setInOutNormalData(context, db, data, inputData, 0);
				}
				else if (type == SmsParser.IN_ATM_SMS)
				{
					resultFlag = setInOutMoveData(context, db, data, inputData);
				}
				else if (type == SmsParser.OUT_ATM_SMS)
				{
					resultFlag = setInOutMoveData(context, db, data, inputData);
				}
			}
			
			
			if (resultFlag == false)
			{
				continue;
			}
			
			NotificationManager nm = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
			
			String notifiedTitle = context.getString(R.string.app_name) + " 문자자동화 입력";
			String typeString = "";
			
			switch (type)
			{
				case SmsParser.IN_SMS:
					typeString = "수입";
					break;
				case SmsParser.OUT_SMS:
					typeString = "지출";
					break;
				case SmsParser.IN_ATM_SMS:
					typeString = "이동";
					break;
				case SmsParser.OUT_ATM_SMS:
					typeString = "이동";
					break;
				default:
					break;
			}
		
			String notifiedMessage = inputData.getName() + " / " + inputData.getMoney() + "원(" + typeString + ") / " + inputData.getMemo1();
			
			NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext());
			
			builder.setSmallIcon(R.drawable.ic_home);
            builder.setContentTitle(notifiedTitle);
            builder.setContentText(notifiedMessage);
            builder.setAutoCancel(true); // 알림바에서 자동 삭제
//            builder.setVibrate(new long[]{1000, 2000}); // 진동
            
            Intent intent2 = new Intent(getApplicationContext(), IntroActivity.class);
            PendingIntent pIntent = PendingIntent.getActivity(context.getApplicationContext(), (int)System.currentTimeMillis(), intent2, Intent.FLAG_ACTIVITY_NEW_TASK);
            builder.setContentIntent(pIntent);
            
            nm.notify((int)System.currentTimeMillis(), builder.build());
		}
	}
	
	private boolean setInOutNormalData(Context context, DbAdapter db, SmsData data, SmsInputData inputData, int flag)
	{
		DbInsertQuery query = null;
		MilkManager milkManager = null;
		
		try
		{
			milkManager = new MilkManager(context, db);
			query = new DbInsertQuery(context, db);
			
			query.setBeginTansaction();
			
			HashMap<String, String> map = new HashMap<String, String>();
			
			if (flag == 0)
			{
				map.put("type", "0");
				map.put("subcategory", context.getString(R.string.out));
			}
			else if (flag == 1)
			{
				map.put("type", "1");
				map.put("subcategory", context.getString(R.string.in));
			}
			else if (flag == 4)
			{
				map.put("type", "4");
				map.put("subcategory", context.getString(R.string.cardcost));
			}
			
			map.put("kind", "0");
			
			map.put("asset", data.getAsset());
			map.put("name", data.getCardname());
			map.put("maincategory", "문자자동화");
			map.put("date", inputData.getDate());
			
			setNowTime();
			map.put("ampm", MilkUtil.getAmPm(am_pm));
			map.put("timehour", hour);
			map.put("timeminute", minute);
			
			map.put("money", inputData.getMoney());
			map.put("memo", inputData.getMemo1());
			
			query.setInOut(map);
			
			if (flag == 0 || flag == 4)
			{
				milkManager.setAssetMoney(milkManager.getAssetId(data.getAsset()), data.getCardname(),
						inputData.getMoney(), 0);
			}
			else
			{
				milkManager.setAssetMoney(milkManager.getAssetId(data.getAsset()), data.getCardname(),
						inputData.getMoney(), 1);
			}
			
			query.setSuccessful();
		} catch (Exception e)
		{
			e.printStackTrace();
			return false;
		} finally {
			try
			{
				query.setEndTansaction();
			} catch (Exception e)
			{
				e.printStackTrace();
				return false;
			}
		}
		
		return true;
	}
	
	private boolean setInOutMoveData(Context context, DbAdapter db, SmsData data, SmsInputData inputData)
	{
		DbInsertQuery query = null;
		MilkManager milkManager = null;
		
		try
		{
			milkManager = new MilkManager(context, db);
			query = new DbInsertQuery(context, db);
			
			query.setBeginTansaction();
			
			HashMap<String, String> map = new HashMap<String, String>();
			
			map.put("type", "2");
			map.put("kind", "0");
			
			map.put("asset", data.getAsset());
			map.put("subasset", data.getSubAsset());
			map.put("name", data.getCardname());
			map.put("subname", data.getSubCardname());
			
			map.put("maincategory", "문자자동화");
			map.put("subcategory", map.put("subcategory", context.getString(R.string.move)));
			map.put("date", inputData.getDate());
			
			setNowTime();
			map.put("ampm", MilkUtil.getAmPm(am_pm));
			map.put("timehour", hour);
			map.put("timeminute", minute);
			
			map.put("money", inputData.getMoney());
			map.put("memo", inputData.getMemo1());
			
			query.setInOut(map);
			
			milkManager.setAssetMoney(milkManager.getAssetId(data.getAsset()), data.getCardname(),
					inputData.getMoney(), 0);
			
			milkManager.setAssetMoney(milkManager.getAssetId(data.getSubAsset()), data.getSubCardname(),
					inputData.getMoney(), 1);
			
			query.setSuccessful();
		} catch (Exception e)
		{
			e.printStackTrace();
			return false;
		} finally {
			try
			{
				query.setEndTansaction();
			} catch (Exception e)
			{
				e.printStackTrace();
				return false;
			}
		}
		
		return true;
	}
	
	private void setNowTime()
	{
		Calendar cal = Calendar.getInstance();
		
		if (cal.get(Calendar.AM_PM) == Calendar.AM)
		{
			am_pm = "AM";
		}
		else
		{
			am_pm = "PM";
		}
		
		if (cal.get(Calendar.HOUR) == 0)
		{
			hour = "12";
		}
		else
		{
			if (cal.get(Calendar.HOUR) < 10)
			{
				hour = "0" + cal.get(Calendar.HOUR);
			}
			else
			{
				hour = cal.get(Calendar.HOUR) + "";
			}
		}
		
		if (cal.get(Calendar.MINUTE) < 10)
		{
			minute = "0" + cal.get(Calendar.MINUTE);
		}
		else
		{
			minute = cal.get(Calendar.MINUTE) + "";
		}
	}
}
